import {Dialog} from '@lowcode/jpaas-common-lib'
import OsDimensionApi from "@/api/user/org/osDimension";
import OsGroupApi from "@/api/user/org/osGroup";
import SysMenuApi from "@/api/system/core/sysMenu";
import DialogBox from "@/assets/js/DialogBox";
import OsGroupMenuApi from '@/api/user/org/osGroupMenu';

export default {
    data() {
        return {
            dimData: [],
            dimId: '',
            boListKey: '',
            initRankLevel: '',
            orgData: [],
            permissions: [],
            treeCheck: false,
            pidSet: [],
            groupId: '',
            allMenusList: [],
            checkedKeys: [],
            halfCheckedKeys: [],
            selectRowListKeys: [],
            selectRowFieldKeys: [],
            grantLists: [],
            grantFields: [],
            grantFieldColumns: [{title: this.$ti18('form.fieldName','字段名称','osGroup'), dataIndex: 'header', width: 180},
                {title: this.$ti18('form.fieldKey','字段Key','osGroup'), dataIndex: 'field', width: 180}],
            //暂存父节点Id
            parentIds: [],

        }
    },
    watch: {
        '$route': {
            handler: function (val) {
                this.loadAppMenus();
            },
            deep: true
        }
    },
    created() {
        this.loadDims();
        this.loadAppMenus();
    },
    methods: {
        loadDims() {
            OsDimensionApi.getDimList().then(res => {
                const dimData = res.data;
                this.dimData = dimData.map(dim => {
                    return {value: dim.dimId, label: dim.name, showType: dim.showType};
                })
                if (this.dimData.length > 0) {
                    this.dimId = this.dimData[0].value;
                    //roleType:标记该功能需要树形结构
                    this.loadDeps({dimId: this.dimData[0].value, initRankLevel: this.initRankLevel});
                }
            })
        },
        loadDeps(params) {
            OsGroupApi.getGroupListByDimId(params).then(resp => {
                let data = resp.data;
                let temp = [];
                for (let i = 0; i < data.length; i++) {
                    var rs = data[i];

                    var _isLeaf = rs.childAmount == 0 ? true : false;
                    temp.push({title: rs.name, groupId: rs.groupId, key: rs.key, isLeaf: _isLeaf})
                }

                this.orgData = [...temp];
            })
        },
        loadAppMenus() {
            let self_ = this;
            SysMenuApi.selectMenus({type: 'group'}).then(res => {
                self_.allMenusList = res;
                self_.permissions = [];
                self_.buildtree(res, self_.permissions, '0')
            })
        },
        buildtree(list, permissions, parentId) {
            let self_=this;
            list.forEach(item => {
                if (item.parentId === parentId) {
                    var child = {
                        key: item.id,
                        title: self_.$i18(item.name,'菜单名称'),
                        parentId: item.parentId,
                        boListKey: item.boListKey,
                        slots: {icon: item.menuType},
                        children: []
                    }
                    this.buildtree(list, child.children, item.id)
                    permissions.push(child)
                }
            })
        },
        //选中组织维度节点
        selectDimNode(selKeys, e) {

            this.dimId = selKeys;
            this.orgData = [];
            this.loadDeps({dimId: selKeys, initRankLevel: this.initRankLevel, roleType: "tree"});
            this.$refs.rxTree.collapseAll();
            this.groupId = '';
            this.boListKey = '';
            this.grantLists = [];
            this.grantFields = [];
            this.selectRowListKeys = [];
            this.selectRowFieldKeys = [];

            for(let i=0; i<this.dimData.length; i++){
                if(this.dimData[i].value == selKeys){
                    if(this.dimData[i].showType == 'TREE'){
                        this.showGroupContainsSub = true;
                    }else{
                        this.showGroupContainsSub = false;
                    }

                    break;
                }

            }

        },
        //加载左树下的子节点
        onLoadGroupTree(treeNode) {
            if (treeNode.dataRef.children) {
                return;
            }
            return OsGroupApi.getParentGroup(treeNode.dataRef.groupId).then(data => {
                let treeData = [];
                for (let i = 0; i < data.length; i++) {
                    var rs = data[i];
                    var _isLeaf = rs.childAmount == 0 ? true : false;
                    treeData.push({title: rs.name, groupId: rs.groupId, key: rs.key, isLeaf: _isLeaf})
                }
                var orgData = this.getGroupTree(this.orgData, treeNode.dataRef.groupId, treeData);
                this.orgData = [...orgData];
            });
        },
        getGroupTree(orgData, groupId, treeData) {
            if (treeData.length > 0) {
                for (var i = 0; i < orgData.length; i++) {
                    if (orgData[i].groupId == groupId) {
                        orgData[i].children = treeData;
                        break;
                    }
                    if (orgData[i].children) {
                        this.getGroupTree(orgData[i].children, groupId, treeData);
                    }
                }
            }
            return orgData;
        },
        //选中用户组树节点
        selectGroupNode(selKeys, e) {
            var self_ = this;
            self_.checkStrictly = true;
            let node = e.node.dataRef;
            this.groupId = node.groupId;
            //注释点击查询
            // if (this.groupId) {
            //     self_.checkedKeys = [];
            //
            //     OsGroupMenuApi.findContainsSub({groupId: this.groupId}).then(res => {
            //         var data = res.data;
            //         if(data == "YES"){
            //             self_.groupContainsSub = true;
            //         }else {
            //             self_.groupContainsSub = false;
            //         }
            //     })
            //
            //     OsGroupMenuApi.findMenuListByGroupId({groupId: this.groupId}).then(res => {
            //         var data = res.data;
            //         for (var i = 0; i < data.length; i++) {
            //             self_.checkedKeys.push(data[i])
            //         }
            //         self_.parentIds = [];
            //     })
            // }
        },
        onCheck(checkedKeys, info) {
            if (!this.treeCheck) this.treeCheck = true;
            //非级联选择
            if (this.checkStrictly) {
                this.checkedKeys = checkedKeys.checked;
                if (info.checked) {
                    this.checkedParent(info.node.dataRef.key);
                }
            } else {
                this.checkedKeys = checkedKeys;
                //如果选中的是父节点则去除父节点
                if (this.parentIds) {
                    for (let i = 0; i < this.parentIds.length; i++) {
                        if (this.parentIds[i] == info.node.dataRef.key) {
                            this.parentIds.splice(i, 1);
                            i--;
                        }
                    }
                }
            }
        },
        //勾选父节点
        checkedParent(id) {
            var menu = this.getMenuById(id, this.permissions);
            if (menu.parentId && menu.parentId != '0') {
                var parentId = this.checkedKeys.find(item => item == menu.parentId);
                if (!parentId) {
                    this.checkedKeys.push(menu.parentId);
                }
                this.checkedParent(menu.parentId);
            }
        },
        //根据id获取菜单
        getMenuById(id, menus) {
            var menu;
            for (var i = 0; i < menus.length; i++) {
                if (menus[i].key == id) {
                    menu = menus[i];
                    break;
                } else {
                    if (menus[i].children && menus[i].children) {
                        menu = this.getMenuById(id, menus[i].children);
                        if (menu) break;
                    }
                }
            }
            return menu;
        },
        selUserData(vm, e) {
            Dialog.openUserDialog({
                curVm: this, data: {single: false}, widthHeight: ['800px', '600px']
            }, function (self, data) {
                var ids = [];
                var names = [];
                for (var i = 0; i < data.length; i++) {
                    ids.push(data[i].userId);
                    names.push(data[i].fullName);
                }
                e.record[e.field] = ids.join(',');
                e.record[e.field + '_name'] = names.join(',');
                e.blur(e.index, e.field, e.text, e.record);
            })
        },
        selGroupData(vm, e) {
            Dialog.openGroupDialog({
                curVm: this, data: {single: false}, widthHeight: ['900px', '600px']
            }, function (self, data) {
                var ids = [];
                var names = [];
                for (var i = 0; i < data.length; i++) {
                    ids.push(data[i].groupId);
                    names.push(data[i].name);
                }
                e.record[e.field] = ids.join(',');
                e.record[e.field + '_name'] = names.join(',');
                e.blur(e.index, e.field, e.text, e.record);
            })
        },
        selTenantData(vm, e) {

        },
        rangSetDlg(vm, e) {
            var config = {
                curVm: this, widthHeight: ['800px', '600px'],
                data: {scope: e.record[e.field], scope_name: e.record[e.field + '_name'], configs: e.record['configs']}
            };
            DialogBox.openFieldRangConfig(config, function (data) {
                e.record[e.field] = data.scope;
                e.record[e.field + '_name'] = data.scope_name;
                e.record['configs'] = data.configs;
                e.blur(e.index, e.field, e.text, e.record);
            })
        },
        gridChangeSelect(value, record, field) {
            var keys = [];
            var labels = [];
            for (var i = 0; i < value.length; i++) {
                keys.push(value[i].key);
                labels.push(value[i].label);
            }
            record[field] = keys.join(',');
            record[field + '_name'] = labels.join(',');
        },
        getSelectData(record) {
            return JSON.parse(record.configs.selDatas);
        },
        showDialog(vm, e) {
            DialogBox.dialog({key: e.record.configs.dialog}, {
                curVm: vm
            }, function (action,data) {
                var rows = data.rows || data;
                var labels = [];
                var values = [];
                for (var i = 0; i < rows.length; i++) {
                    labels.push(rows[i][e.record.configs.textField]);
                    values.push(rows[i][e.record.configs.valueField]);
                }
                e.record[e.field] = values.join(',');
                e.record[e.field + '_name'] = labels.join(',');
                e.blur(e.index, e.field, e.text, e.record);
            });
        },
        saveOsGroupMenu() {
            const data = []
            var this_ = this;
            if (!this_.groupId) {
                this_.$message.error(this_.$ti18('groupRel.unjoinTips','请选择用户组!','osGroup'));
                return;
            }
            if (!this_.checkedKeys.length > 0) {
                this_.$message.warning(this_.$ti18('msa.selLeastAuthTips','请至少选择一个权限','osGroup'));
                return;
            }
            var checkedKeys_ = JSON.parse(JSON.stringify(this.checkedKeys));
            checkedKeys_.push(...this.parentIds);
            //去重
            checkedKeys_ = Array.from(new Set(checkedKeys_));
            this.allMenusList.forEach(item => {
                checkedKeys_.forEach(checkId => {
                    if (item.id === checkId) {
                        var groupMenu = {
                            groupId: this_.groupId,
                            menuId: item.id,
                            appId: item.appId,
                            type: item.menuType,
                            name:item.name
                        }
                        data.push(groupMenu)
                    }
                })
            })
            OsGroupMenuApi.saveOsGroupMenu(Object.assign(data), this_.groupId,this_.groupContainsSub,this_.dimId);
        }
    }
}